//
//  NSString+Helper.m
//  ruying
//
//  Created by yqh on 2019/2/23.
//  Copyright © 2019年 林伟钦. All rights reserved.
//

#import "NSString+Helper.h"
#import <YYText/YYText.h>

@implementation NSString (Helper)

- (CGFloat)widthForStringWithFont:(UIFont *)font maxHeight:(CGFloat)height {
    CGRect sizeToFit = [self boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    
    return sizeToFit.size.width + 1;
}

- (CGFloat)heightForStringWithFont:(UIFont *)font maxWidth:(CGFloat)width {
    CGRect sizeToFit = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    
    return sizeToFit.size.height + 1;
}

- (CGFloat)heightForStringWithFont:(UIFont *)font lineSpacing:(CGFloat)lineSpacing maxWidth:(CGFloat)width {
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = lineSpacing;
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:style};
    CGRect sizeToFit = [self boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    return sizeToFit.size.height + 1;
}

- (CGFloat)heightForYYTextWithFont:(UIFont *)font lineSpacing:(CGFloat)lineSpacing maxWidth:(CGFloat)width {
    NSMutableAttributedString *attring = [[NSMutableAttributedString alloc] initWithString:self];
    attring.yy_font = font;
    attring.yy_lineSpacing = lineSpacing;
    
    CGSize size = CGSizeMake(width, CGFLOAT_MAX);
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:attring];
    
    return layout.textBoundingSize.height + 1;
}


+ (NSAttributedString *)getAttributedStringWithString:(NSString *)string font:(UIFont *)font lineSpacing:(CGFloat)lineSpacing {
    
    if (string.length == 0) {
        return nil;
    }
    
    NSMutableAttributedString *astring = [[NSMutableAttributedString alloc] initWithString:string];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = lineSpacing;
    
    NSRange range = NSMakeRange(0, string.length);
    [astring addAttribute:NSParagraphStyleAttributeName value:style range:range];
    [astring addAttribute:NSFontAttributeName value:font range:range];
    
    return astring;
}

@end
